package com.mathlearning.auth.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ApiResponse<?> handleBusinessException(BusinessException e) {
        logger.warn("业务异常: {}", e.getMessage());
        return ApiResponse.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<?> handleValidationException(MethodArgumentNotValidException e) {
        logger.warn("参数验证失败: {}", e.getMessage());
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        if (!fieldErrors.isEmpty()) {
            FieldError firstError = fieldErrors.get(0);
            String errorMessage = firstError.getDefaultMessage();
            return ApiResponse.error(400, errorMessage != null ? errorMessage : "参数验证失败");
        }
        return ApiResponse.error(400, "参数验证失败");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ApiResponse<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        logger.warn("文件上传大小超出限制: {}", e.getMessage());
        return ApiResponse.error(413, "文件大小超出限制，最大支持500MB");
    }

    @ExceptionHandler(FileSizeLimitExceededException.class)
    public ApiResponse<?> handleFileSizeLimitExceededException(FileSizeLimitExceededException e) {
        logger.warn("文件大小超出限制: {}", e.getMessage());
        return ApiResponse.error(413, "文件大小超出限制，最大支持500MB");
    }

    @ExceptionHandler(MultipartException.class)
    public ApiResponse<?> handleMultipartException(MultipartException e) {
        logger.warn("文件上传格式错误: {}", e.getMessage());
        return ApiResponse.error(400, "请使用正确的文件上传格式，确保使用 multipart/form-data");
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<?> handleException(Exception e) {
        logger.error("系统异常", e);
        return ApiResponse.error(500, "系统异常，请稍后重试");
    }
}

